//
//  ChooseTaoCanViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/21/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ChooseTaoCanViewController.h"
#import "SynDetailsSecondCell.h"

#import "ChooseCameraManViewController.h"

#import "AppointmentShangMenTwoViewController.h"
#import "AppointmentYinPenViewController.h"

#import "ShowRecommendWebViewController.h"

#import "ShowWebViewController.h"

@interface ChooseTaoCanViewController ()
{
    NSArray * addressArray; //拍摄地点
    NSArray * modelArray;   //服装造型
    NSArray * albumArray;   //相册数量
    
    BOOL isBirthSence;     //出生照场景  yes支持上门拍摄和医院拍摄 no支持上门拍摄和影棚拍摄
    
    NSMutableDictionary *  senceDict;
    int selectSence;    //选中的场景
    int  addressType;  //1表示到家 2表示影棚 3表示医院
    int  modelType;    //1表示3组 2表示4组 3表示5组
    int  albumType;    //1表示相册数量0 2表示相册数量1 3表示相册数量2
    
    NSMutableDictionary * presentSenceDict;
    UIButton * rightBtn;
}
@end

@implementation ChooseTaoCanViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleLabel.text = @"选择套餐";
    
    isFirst = YES;
    didianNumber = 1;
    fuzhuangNum = @"4";
    xiangceNum = @"1";
    
    senceArray = [[NSMutableArray alloc] init];
    taocanDataArray = [[NSMutableArray alloc] init];
    senceDict = [[NSMutableDictionary alloc] init];
    taocanDict = [[NSMutableDictionary alloc] init];
    presentSenceDict = [[NSMutableDictionary alloc] init];
    addressArray = @[@"到家拍摄",@"影棚拍摄"];
    modelArray = @[@"4组造型",@"5组造型"];
    albumArray = @[@"要相册",@"不要相册"];
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, self.contentView.frame.size.height-UI_TAB_BAR_HEIGHT) style:UITableViewStylePlain];
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.hidden = YES;
    [self.contentView addSubview:mTableView];
    
    [self initFootViews];
    
    [self getSceneDatas];
    
    [self getAllTaocanData];
    
    rightBtn = [self createButtonOnNavigationWithRect:CGRectMake(UI_SCREEN_WIDTH-50, 0,40, 44) normalImg:LOADIMAGE(@"i@2x") highlightImg:LOADIMAGE(@"i@2x")];
    [rightBtn setTitleColor:self.titleLabel.textColor forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnCick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:rightBtn];
    
}

#pragma mark
#pragma mark 右上角按钮点击事件
-(void)rightBtnCick
{
    ShowRecommendWebViewController * showvc = [[ShowRecommendWebViewController alloc] init];
    [self.navigationController pushViewController:showvc animated:YES];
}


#pragma mark footview 布局
-(void)initFootViews
{
    footView = [UIView initViewRect:CGRectMake(0,self.contentView.frame.size.height-49, UI_SCREEN_WIDTH, 50) andBackGroudColor:UIColorFromRGB(0xf1f1f1)];
    [self.contentView addSubview:footView];
    
    NSString * str;
    if (self.type==1){
        str = @"选中该套餐";
        //        [self getPhotoMode];
    }else{
        str = @"确认下单";
    }
    
    footPriceLB = [UILabel initLabelText:@"" andRect:CGRectMake(15,13, 200, 50) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:22] andTextColor:UIColorFromRGB(0xff6800) andTextAlignment:NSTextAlignmentLeft];
    [footPriceLB sizeToFit];
    [footView addSubview:footPriceLB];
    
    marketPriceLB = [UILabel initLabelText:@"" andRect:CGRectMake(VIEW_POINT_MAX_X(footPriceLB),22, 60, 15) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:12] andTextColor:UIColorFromRGB(0x929292) andTextAlignment:NSTextAlignmentLeft];
    [footView addSubview:marketPriceLB];
    
    line = [UIView initViewRect:CGRectMake(VIEW_POINT_MAX_X(footPriceLB), 29, marketPriceLB.text.length*7.5, 1) andBackGroudColor:UIColorFromRGB(0x929292)];
    [footView addSubview:line];
    
    
    UIButton * sureBtn = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-111-10,9, 111,32) btnImage:LOADIMAGE(@"surexiadanbtn@2x") btnTitle:@"选中该套餐" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:sureBtn];
    
    footView.hidden = YES;
}

- (void)reloadFootViews{
    footPriceLB.frame = CGRectMake(15,13, 200, 50);
    if (IS_NOT_EMPTY(taocanDict[@"Price"])){
        footPriceLB.text = [NSString stringWithFormat:@"￥%@",taocanDict[@"Price"]];
    }else{
        footPriceLB.text = @"无此套餐";
    }
    [footPriceLB sizeToFit];
    
    marketPriceLB.text = taocanDict[@"MarketPrice"];
    marketPriceLB.frame = CGRectMake(VIEW_POINT_MAX_X(footPriceLB),22, 60, 15);
    
    line.frame = CGRectMake(VIEW_POINT_MAX_X(footPriceLB), 29, marketPriceLB.text.length*7.5, 1);
}

#pragma mark
#pragma mark UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 4 || indexPath.row == 6) {
        return 30;
    }else if (indexPath.row == 5) {
        return 200;
    }
    if (indexPath.row == 0){
        return 46+29+9;
    }
    return 46;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            static NSString * cell0 = @"cell";
            ChooseSenceCell * cell = [tableView dequeueReusableCellWithIdentifier:cell0];
            if (cell == nil){
                cell = [[ChooseSenceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell0];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            if (senceArray.count && isFirst) {
                cell.delegate = self;
                cell.dataArray = senceArray;
                
                if ([senceArray count]){
                    UIButton * enabledbtn = (UIButton *)[cell.mScrollView viewWithTag:cell.brithTag];
                    if ([enabledbtn isKindOfClass:[UIButton class]]){
                        if (addressType == 2){
                            enabledbtn.enabled = NO;
                        }else{
                            enabledbtn.enabled = YES;
                            if (addressType == 3){
                                for (UIButton * btn in cell.mScrollView.subviews){
                                    if([btn isKindOfClass:[UIButton class]]){
                                        btn.enabled = btn.tag ==enabledbtn.tag?YES:NO;
                                    }
                                }
                            }
                        }
                    }
                    
                    UIButton * selectbtn = (UIButton *)[cell.mScrollView viewWithTag:selectSence];
                    if ([selectbtn isKindOfClass:[UIButton class]]){
                        selectbtn.selected = YES;
                    }
                }
                
                UIButton * btn = (UIButton *)[cell.contentView viewWithTag:1000];
                [cell buttonClick:btn];

                isFirst = NO;
            }
            
            
            return cell;
        }
            break;
        case 1:
        case 2:
        case 3:
        {
            static NSString * cellName = @"cell1";
            ChooseTaoCanCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
            if (cell == nil){
                cell = [[ChooseTaoCanCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.delegate = self;
            if (indexPath.row == 1){
                cell.typeLB.text = @"拍摄地点";
                cell.dataArray = addressArray;
                
                if (isBirthSence){
                    cell.secondBtn.enabled = NO;
                }else{
                    cell.thirdBtn.enabled = NO;
                }
                
                if (addressType ==1){
                    cell.firstBtn.selected = YES;
                }else if (addressType == 2){
                    cell.secondBtn.selected = YES;
                }else if (addressType == 3){
                    cell.thirdBtn.selected = YES;
                }
                
            }else if (indexPath.row == 2){
                cell.typeLB.text = @"服装造型";
                cell.dataArray = modelArray;
                if (modelType == 1){
                    cell.firstBtn.selected = YES;
                }else if (modelType == 2){
                    cell.secondBtn.selected = YES;
                }else if (modelType == 3){
                    cell.thirdBtn.selected = YES;
                }
                
            }else if (indexPath.row == 3){
                cell.typeLB.text = @"相册";
                cell.dataArray = albumArray;
                if (albumType == 1){
                    cell.firstBtn.selected = YES;
                }else{
                    cell.secondBtn.selected = YES;
                }
            }
            return cell;
        }
            break;
        case 4:
        {
            NSString * cellIde = @"cell4";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                cell.contentView.backgroundColor = UIColorFromRGB(0xf1f1f1);
                
                UILabel * lab = [UILabel initLabelText:_taocanType andRect:CGRectMake(15, 0, UI_SCREEN_WIDTH-30, 30) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:16] andTextColor:UIColorFromRGB(0x626262) andTextAlignment:NSTextAlignmentLeft];
                [cell.contentView addSubview:lab];
                
                lab.tag = 12345;
            }
            UILabel * lab = (UILabel *)[cell.contentView viewWithTag:12345];
            lab.text = _taocanType;
            
            return cell;
        }
            break;
        case 5:
        {
            static NSString * cellName = @"cell5";
            SynDetailsFirstCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
            if (cell == nil){
                cell = [[SynDetailsFirstCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.type = 1;
            }
            cell.dataDict = taocanDict;
            cell.delegate = self;
            return cell;
        }
            break;
        case 6:
        {
            static NSString * cellName = @"cell6";
            SynDetailsSecondCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
            if (cell == nil){
                cell = [[SynDetailsSecondCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
            break;
        default:
            break;
    }
    
    static NSString * cellName = @"cell0";
    ChooseTaoCanCell * cell0 = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell0 == nil){
        cell0 = [[ChooseTaoCanCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell0.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    return;
}

#pragma mark 
#pragma mark ChooseSenceCell Delegate 选择场景
-(void)chooseSence:(NSDictionary *)mDict andchooseindex:(int)index
{
    
    if ([mDict[@"PhotoMode"] count]) {
        presentSenceDict = [[NSMutableDictionary alloc] initWithDictionary:mDict];
        for (NSDictionary * dict in mDict[@"PhotoMode"]) {
            if (didianNumber == 1 && [dict[@"Cate"] intValue] == 0) {
                senceDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                didianID = senceDict[@"PMID"];
                break;
            }else if (didianNumber == 2 && [dict[@"Cate"] intValue] == 2) {
                senceDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                didianID = senceDict[@"PMID"];
                break;
            }
        }
    }
    selectSence = index;
//    modelType = 1;
    if ([mDict[@"PageType"] intValue]==2){
        isBirthSence = YES;
        didianNumber = 1;
    }else{
        isBirthSence = NO;
    }
    
    changjingID = mDict[@"SceneID"];
    if (didianID && fuzhuangNum) {
        [self chooseTaoCanDict];
    }
    
    [self choosekind:1 andType:didianNumber];

    [mTableView reloadData];
}

#pragma mark
#pragma mark ChooseTaoCanCell Delegate 选择拍摄地点、服装造型、相册数量
-(void)choosekind:(int)mKid andType:(int)mType
{
    switch (mKid) {
        case 1: //拍摄地点
        {
            addressType = mType;
            NSIndexPath *indexPath1=[NSIndexPath indexPathForRow:1 inSection:0];
            [mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1,nil] withRowAnimation:UITableViewRowAnimationNone];
        
            didianNumber = mType;
            
            
            for (NSDictionary * dict in presentSenceDict[@"PhotoMode"]) {
                if (didianNumber == 1 && [dict[@"Cate"] intValue] == 0) {
                    senceDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                    didianID = senceDict[@"PMID"];
                    
                    if (changjingID && fuzhuangNum) {
                        [self chooseTaoCanDict];
                    }
                    
                    break;
                }else if (didianNumber == 2 && [dict[@"Cate"] intValue] == 2) {
                    senceDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                    didianID = senceDict[@"PMID"];
                    
                    if (changjingID && fuzhuangNum) {
                        [self chooseTaoCanDict];
                    }
                    
                    break;
                }
            }
            
        }
            break;
        case 2: //服装造型
        {
//            didianNumber = mType;
            modelType = mType;
            
            
            NSIndexPath *indexPath2=[NSIndexPath indexPathForRow:2 inSection:0];
            [mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath2,nil] withRowAnimation:UITableViewRowAnimationNone];
            
            if (mType == 1) {
                fuzhuangNum = @"4";
            }else{
                fuzhuangNum = @"5";
            }
            
            if (changjingID && didianID && xiangceNum) {
                [self chooseTaoCanDict];
            }
        }
            break;
        case 3: //相册数量
        {
            albumType = mType;
            NSIndexPath *indexPath3=[NSIndexPath indexPathForRow:3 inSection:0];
            [mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath3,nil] withRowAnimation:UITableViewRowAnimationNone];
            
            if (mType == 1) {
                xiangceNum = @"1";
            }else{
                xiangceNum = @"0";
            }
            
            if (changjingID && didianID && fuzhuangNum) {
                [self chooseTaoCanDict];
            }
        }
            break;
        default:
            break;
    }
    
}

#pragma mark
#pragma mark  获取场景信息
-(void)getSceneDatas
{ 
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    ASIHTTPRequest * request = [XDTools postRequestWithDict:@{@"Type":@"2"} API:scene_info];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            
            [senceArray removeAllObjects];
            [senceArray addObjectsFromArray:tmpDict[@"data"]];
            
//            NSIndexPath *indexPath1=[NSIndexPath indexPathForRow:0 inSection:0];
//            [mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1,nil] withRowAnimation:UITableViewRowAnimationNone];
            
            [mTableView reloadData];
            
            if (taocanDataArray.count && senceArray.count) {
                mTableView.hidden = NO;
                footView.hidden = NO;
            }
            
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
}

- (void)getAllTaocanData{
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    ASIHTTPRequest * request = [XDTools postRequestWithDict:@{@"EmplID":[XDTools sharedXDTools].EmplID} API:API_GetSeriesDetail];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            
            taocanDataArray = [NSMutableArray arrayWithArray:tmpDict[@"data"][@"SeriesInfo"]];
            for (int i = 0; i < 3; i++) {
                [self choosekind:i+1 andType:1];
            }
            
            if (taocanDataArray.count && senceArray.count) {
                mTableView.hidden = NO;
                footView.hidden = NO;
            }
            
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


-(void)iconIvClickWithUrl:(NSString *)mUrlString{
    if (IS_NOT_EMPTY(taocanDict[@"Url"])){
        ShowWebViewController * showWebVC = [[ShowWebViewController alloc] init];
        showWebVC.urlstring = taocanDict[@"Url"];
        [self.navigationController pushViewController:showWebVC animated:YES];
    }
}

- (void)chooseTaoCanDict{
    if (taocanDataArray) {
        int i = 0;
        taocanDict = nil;

        for (NSDictionary * dict in taocanDataArray) {
            NSLog(@"fuzhuangNum ---- (%d,%d)    xiangceNum ---- (%d,%d)   PMID ---- %@,%@  changjingID ---- %@,%@",fuzhuangNum.intValue,[dict[@"ModeCount"] intValue],xiangceNum.intValue,[dict[@"XCCount"] intValue],didianID,dict[@"PMID"],changjingID,dict[@"SceneID"]);
            if ([dict[@"SceneID"] isEqualToString:changjingID] &&
                [dict[@"PMID"] isEqualToString:didianID] &&
                [dict[@"ModeCount"] intValue] == fuzhuangNum.intValue &&
                [dict[@"XCCount"] intValue] == xiangceNum.intValue) {
                taocanDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                _taocanType = taocanDict[@"SeriesName"];

                NSIndexPath  * indexPath1 = [NSIndexPath indexPathForRow:4 inSection:0];
                NSIndexPath * indexPath2 = [NSIndexPath indexPathForRow:5 inSection:0];
                NSIndexPath * indexPath3 = [NSIndexPath indexPathForRow:6 inSection:0];
                
                [mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1,indexPath2,indexPath3,nil] withRowAnimation:UITableViewRowAnimationNone];
                
                DDLOG(@"================================");
                
                [self reloadFootViews];
                
                i++;
            }
        }
        if (!i) {
            footPriceLB.text = @"无此套餐";
            [footPriceLB sizeToFit];
            
            line.frame = CGRectMake(VIEW_POINT_MAX_X(footPriceLB), 29, marketPriceLB.text.length*7.5, 1);

            _taocanType = @"";
            [self reloadFootViews];

        }
    }
    DDLOG(@"123456");
}

#pragma mark - 确认下单
- (void)sureBtnClick{
    
    if ([footPriceLB.text isEqualToString:@"无此套餐"]){
        [XDTools showTips:@"无此套餐" toView:self.view];
        return;
    }
    //场景信息
    [XDTools sharedXDTools].SceneID =taocanDict[@"SceneID"];
    [XDTools sharedXDTools].ModeID = taocanDict[@"PMID"];
    
    //套餐信息
    [XDTools sharedXDTools].taocanDesc = @"";
    [XDTools sharedXDTools].taocanPrcie = taocanDict[@"Price"];
    [XDTools sharedXDTools].taocanName = taocanDict[@"SeriesName"];
    [XDTools sharedXDTools].taocanImgUrl = taocanDict[@"SeriesPhotoID"];
    [XDTools sharedXDTools].SeriesID = taocanDict[@"SeriesID"];
    [XDTools sharedXDTools].taocanMarketPrice = taocanDict[@"MarketPrice"];
    
    if (didianNumber == 1){
        [XDTools sharedXDTools].PSID = nil;
        AppointmentShangMenTwoViewController * shangmenVC = [[AppointmentShangMenTwoViewController alloc] init];
        shangmenVC.comeSuperVC =YES;
        [self.navigationController pushViewController:shangmenVC animated:YES];
    }else if (didianNumber == 2){
        AppointmentYinPenViewController * yinpenVC = [[AppointmentYinPenViewController alloc] init];
        [self.navigationController pushViewController:yinpenVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
